昨天將地址的原始資料整理成
節點與相連節點的資料結構
今天繼續看接下來的部分
節錄覺得實用的描述
如果你正從物件導向程式設計下手,可能開始為各種元素定義物件,然後為類別設定屬性,儲存它們當前狀態,但某些東西的感覺上像是物件並不代表可以自動帶入為程式中的物件。反射性為應用程式中的每個概念撰寫類別,往往會留下一組相互關聯的物件。每個物件內部各自有不斷變化的狀態。這一類的程式通常最後都難以理解,因此容易發生程式中斷的問題。
相反的,要定義最小的集合值,將村莊的狀態濃縮在集合值裡,集合值包含所有機器人當前位置和所有尚未配送的包裹,每個包裹下有目前所在位置和目的地位置
機器人移動時不改變這個狀態,等機器人移動後才計算出新的狀態
以下為範例程式碼
// define the smallest collections of parcel state and places
      class VillageState {
        constructor(place, parcels) {
          this.place = place;
          this.parcels = parcels;
        }
        move(destination) {
          /* 
          check if the destination is connect to the current place
          if not, the moving is invalid, so stop and return the original state
          if true, update the state of parcels
           */
          if (!roadGraph[this.place].includes(destination)) {
            return this;
          } else {
            let parcels = this.parcels
              /*
              if p.place equals to this place, means the parcel has arrived
              update the current place as destination then filter out the arrived parcel
              */
              .map((p) => {
                console.log(p);
                if (p.place !== this.place) return p;
                return { place: destination, address: p.address };
              })
              .filter((p) => p.place !== p.address);
            return new VillageState(destination, parcels);
          }
        }
      }
const with primitive valueObject.freeze() can prevent Object from mutation, but